<?php

namespace App\Admin\Actions\BlindBoxAction;

use App\Models\BlindBoxProduct;
use App\Models\BlindBoxLevelValue;
use App\Models\Product;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Brick\Math\RoundingMode;


class RefreshBlindBoxRate extends RowAction
{
    public $name = '刷新盲盒等级概率';
    
    public function handle(Model $model)
    {
    	$id = $model->id;
    	$allProduct = BlindBoxProduct::where("blind_box_id",$id)
    		->with('product')
    		->get()->toArray();
    	if(empty($allProduct)){
    		return $this->response()->error('无商品数据')->refresh();
    	}

    	$hasLowestPrice = 0;
    	$maxLevelProduct = [];

    	foreach($allProduct as $k =>$v){

    		if(isset($maxLevelProduct[$v['blind_box_level_id']])){
    			if(big_decimal($v['product']['price_lowest_cost'])->isGreaterThan($maxLevelProduct[$v['blind_box_level_id']]['price'])){
    				unset($allProduct[$maxLevelProduct[$v['blind_box_level_id']]['key']]);
    				$maxLevelProduct[$v['blind_box_level_id']]['price'] = $v['product']['price_lowest_cost'];
    				$maxLevelProduct[$v['blind_box_level_id']]['key'] = $k;
    			}else{
					unset($allProduct[$k]);
    			}
    		}else{
				$maxLevelProduct[$v['blind_box_level_id']]['price'] = $v['product']['price_lowest_cost'];
    			$maxLevelProduct[$v['blind_box_level_id']]['key'] = $k;
    		}
    		
    	}
    	$allProduct = array_merge($allProduct);

    	$higherProducts = [];
    	$lowerProducts = [];
    	foreach($allProduct as $k => $v){
    		if(big_decimal($v['product']['price_lowest_cost'])->isGreaterThan($model->price)){
    			$higherProducts[$k]['profit'] = big_decimal($v['product']['price_market'])->minus($model->price);
    			$higherProducts[$k]['cost'] =  $v['product']['price_lowest_cost'];
    			$higherProducts[$k]['blind_box_id']  = $v['blind_box_id'];
    			$higherProducts[$k]['blind_box_level_id'] = $v['blind_box_level_id'] ;
    		}else{
    			$lowerProducts[$k]['profit'] = big_decimal($model->price)->minus($v['product']['price_lowest_cost']);
    			$lowerProducts[$k]['cost'] =  $v['product']['price_lowest_cost'];
    			$lowerProducts[$k]['blind_box_id']  = $v['blind_box_id'];
    			$lowerProducts[$k]['blind_box_level_id'] = $v['blind_box_level_id'] ;
    		}
    	}

    	if(empty($higherProducts)){
    		return $this->response()->error('无超过盲盒本身价值的商品')->refresh();
    	}
    	if(empty($lowerProducts)){
    		return $this->response()->error('无低于盲盒本身价值的商品')->refresh();
    	}

    	

    	$minPrice = min(array_column($lowerProducts,'profit'));
    	$sumPrice = array_sum(array_column($lowerProducts,'cost'));
    	$count = count($higherProducts);
    	$lowerRateAll  = big_decimal(1);

    	$insertArr = [];
    	$i = 0;
    	foreach($higherProducts  as  $hk => $hv){
    		$times= $hv['profit']->dividedBy($minPrice, 2 , RoundingMode::HALF_UP);
    		$higherProducts[$hk]['rate'] = big_decimal(1)->dividedBy(big_decimal($count) , 4 , RoundingMode::HALF_UP)->dividedBy(big_decimal(1)->plus($times) , 4 , RoundingMode::HALF_UP);

    		$lowerRateAll = $lowerRateAll->minus($higherProducts[$hk]['rate']);

    		$insertArr[$i]['blind_box_id'] = $hv['blind_box_id'];
    		$insertArr[$i]['blind_box_level_id'] = $hv['blind_box_level_id'];
    		$insertArr[$i]['rate'] = $higherProducts[$hk]['rate']->multipliedBy(100);
    		$i++;
    	}
    	
    	foreach($lowerProducts as $lk => $lv){

    		$insertArr[$i]['blind_box_id'] = $lv['blind_box_id'];
    		$insertArr[$i]['blind_box_level_id'] = $lv['blind_box_level_id'];
    		$insertArr[$i]['rate'] = $lowerRateAll->multipliedBy(big_decimal($lv['cost'])->dividedBy(big_decimal($sumPrice) , 2 , RoundingMode::HALF_UP))->multipliedBy(100);
    		$i++;

    	}

    	BlindBoxLevelValue::query()
    		->where('blind_box_id',$insertArr[0]['blind_box_id'])->update([
		        'is_used' => false,
		    ]);

		BlindBoxLevelValue::insert($insertArr);
    	
		return $this->response()->success('盲盒抽奖概率已更新')->refresh();
    }
	
	public function dialog()
	{
		$this->confirm('确定刷新盲盒等级概率?');
	}
}
